<template>
	<div
		v-loading.fullscreen.lock="loadingIntegration"
	   element-loading-text="视频整合中，整合要花点时间处理..."
	   element-loading-background="rgba(0, 0, 0, 0.1)">
		<!--  -->
		<div class="pointMark_video">
				<video-player  class="video-player vjs-custom-skin" id="videoPlayer"
				     ref="videoPlayer"
				     :playsinline="true"
				     :options="playerOptions"
				     @play="onPlayerPlay($event)"
					@pause="onPlayerPause($event)"
				></video-player>
		
		</div>
		<!--  -->
		<div class="fragment">
			<p class="tipcd">裁剪原片</p>
			<div class="fragment_cont">
					<ul class="clear box fl">
						<template v-for="(item ,inx) of fixVideoList" >
							<li class="fragment_ls fl" @click="switchPlayurl(item, inx)">
								<img :src="`${item.thumbnail}`" >
								<div v-if="inx > 0"   style="text-align: right"><i @click.stop="deleteOtherVideo(inx)" class="el-icon-circle-close" style="margin-top: 0px;"></i></div>
							</li>
						</template>
						<li class="fragmentUp box fl" @click="uploadMode = true">
							<i class="el-icon-picture-outline"></i>
							<p>点击上传</p>
						</li>
						
					</ul>
			</div>
		</div>
		<!--  -->
		<div class="videoIntegration_table">
			<p class="tipcd">截取时长</p>
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="85px" class="demo-ruleForm">
				<div class="videoIntegration_tm clear">
					<el-form-item label="开始时间" prop="startTime">
						<span>
							<el-time-picker
							   v-model="ruleForm.startTime"
							   value-format="HH:mm:ss"
							   :arrow-control="true"
							   :picker-options="{
							   	 format: 'HH:mm:ss',
							     selectableRange: '00:00:00-'+timeMax
							   }"
							   placeholder="任意时间点">
							 </el-time-picker>
							
						</span>
						<i class="el-icon-location" @click="getVideoPlayTime(1)"></i>
					</el-form-item>
					<!--  -->
					<el-form-item label="结束时间" prop="endTime">
						<span>
							<el-time-picker
							   v-model="ruleForm.endTime"
							   value-format="HH:mm:ss"
							   :arrow-control="true"
							   :picker-options="{
							   	 format: 'HH:mm:ss',
							     selectableRange: '00:00:00-'+timeMax
							   }"
							   placeholder="任意时间点">
							 </el-time-picker>
						</span>
						<i class="el-icon-location" @click="getVideoPlayTime(2)"></i>
					</el-form-item>
					<!--  -->
					<el-form-item label="截取时长" prop="len">
						<span class="t_length" v-model="ruleForm.len">{{ ruleForm.len }}</span>
					</el-form-item>
				</div>

				<el-form-item class="buttonCSS videoIntegration_btn" label-width="0" >
					<!-- <el-button @click="resetForm('ruleForm')" type="primary" plain>预览片段</el-button> -->
					<el-button type="primary" @click="submitForm('ruleForm')">确定截取</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="publishFrom_table off-cut">
			<template>
				<el-table 
				border
				ref="singleTable"
				:data="fixVideoList"
				highlight-current-row
				style="width: 100%">
					<el-table-column
						type="index"
						label="序号"
						width="50">
					</el-table-column>
					<el-table-column
						property="name"
						label="文件名称"
						align='center'
						width="280"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column
						property="timerate_show"
						align='center'
						label="最终视频中的时间"
						width="219"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column
						property="times"
						width="150"
						align='center'
						label="截取时长"
						show-overflow-tooltip>
					</el-table-column>
				</el-table>
			</template>
			<div class="interceptBtn buttonCSS">
				<el-button type="primary" class="buttonCSS"  @click="saveInteVideo()">保存</el-button>
			</div>
		</div>
		<!--  -->
		<el-dialog
			title="上传方式"
			:visible.sync="uploadMode"
			width="550px"
			custom-class="uploadMode"
			:before-close="removeFile"
			:close-on-click-modal="false">
				<div class="videoIntegration_xz clear">
					<div>
						<i class="ipm qingjia_icon02"></i>
						<p>本地视频</p>
							<uploader 
							:options="uploadOptions" 
							:autoStart="true" 
							ref="uploader" 
							:file-status-text="statusText" 
							@file-added="fileAdd"
							 @files-submitted="fileSubmit"
							 @file-removed="fileRemoved" 
							 @file-success="fileSuccess"
							  @file-error="fileFail"  
							  class="uploader-example-video">
							    <uploader-unsupport></uploader-unsupport>
							    <uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true"></uploader-btn>
							    <uploader-list  v-if="selectFileShow===false?true:false"></uploader-list>
						   	</uploader>
					</div>
					<div @click="getListBox()">
						<i class="ipm qingjia_icon01"></i>
						<p>关联视频</p>
					</div>
				</div>
		</el-dialog>
		<!--  -->
		<!-- 选择资源 -->
		<el-dialog
			title="选择资源"
			:visible.sync="selectResourceFile"
			width="800px"
			custom-class="alBox"
			:close-on-click-modal="false">
				<uploader :options="uploadOptions" :autoStart="true" ref="uploader" :file-status-text="statusText" @file-added="fileAdd" @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail"  class="uploader-example">
				    <uploader-unsupport></uploader-unsupport>
				    <uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true">选择文件</uploader-btn>
				    <uploader-list  v-if="selectFileShow===false?true:false"></uploader-list>
			   	</uploader>
		</el-dialog>
		<!-- 选择资源 -->
		<el-dialog
			title="选择资源"
			:visible.sync="selectResourceView"
			width="800px"
			custom-class="alBox"
			:close-on-click-modal="false">
			<div class="releaseTK">
				<div class="releaseTK_h clear">

					<div class="resourceSearch fl">
						<el-input placeholder="视频名，教师名" v-model="listParam.keyword" class="input-with-select" @change="getList()">
						  <el-button slot="append" icon="el-icon-search"></el-button>
						</el-input>
					</div>
				</div>
				<!--  -->
				<div class="resourceData"
					v-loading="loading.status"
					:element-loading-text="loading.txt"
				>	
					<template>
						<el-table
						border
						ref="multipleTable"
						highlight-current-row
						@cell-click="selectVideo"
						:data="listData"
						tooltip-effect="dark"
						style="width: 100%"
						>
							<el-table-column
							prop="video_name"
							label="视频名称"
							width="278"
							show-overflow-tooltip>
							</el-table-column>
							<el-table-column
							prop="category"
							label="视频分类"
							align='center'
							width="180"
							show-overflow-tooltip>
							</el-table-column>
							<el-table-column
							prop="type_name"
							label="视频信息"
							align='center'
							width="80"
							show-overflow-tooltip>
							</el-table-column>
							<el-table-column
							prop="create_time"
							label="上传时间"
							align='center'
							width="180"
							show-overflow-tooltip>
							</el-table-column>
						</el-table>
					</template>
					<div class="table-pagination" v-if="total_number > listParam.page_size">
						<el-pagination
						    @size-change="handleSizeChange"
						    @current-change="handleCurrentChange"
						    :current-page="listParam.page_index"
						    :page-sizes="[10, 20, 30, 40, 50, 100]"
						    :page-size="listParam.page_size"
						    layout="total, sizes, prev, pager, next, jumper"
						    :total="total_number">
						</el-pagination>
						<div class="pagination-button" v-if="0">
							<el-button 
								@click="getList"
								type="primary" icon="el-icon-refresh" 
								circle title="刷新数据" size="mini" >
							</el-button>
						</div>
					</div>
				</div>
			</div>
			<div slot="footer" class="dialog-footer releaseTK_btn buttonCSS">
				<el-button type="primary" @click="selectResourceView = false" plain>取 消</el-button>
				<el-button type="primary" @click="comfirmVideo">确 定</el-button>
			</div>
		</el-dialog>
	
	</div>
</template>

<script>
	// import 'vue-video-player'; //video播放器
	// import 'videojs-flash'
	// import SWF_URL from 'videojs-swf/dist/video-js.swf';
	// import "video.js/dist/lang/zh-CN"
	export default {
		props : ['compParam','activeIndex'],
		name: '',
		data() {
			return {
				thisIndex: '7',
				loading:{
					status:false,
					txt:'获取数据...',
				},
	      		listData:[],
		    	listParam:{
		       		keyword: '',
		       		type:-1,
		       		page_index:1,
		       		page_size:10,
		        },
		        total_number:0,
		        tempVideo:null,
				selectFileShow:true,//是否显示选择文件按钮,
				uploadOptions: {
			          target: this.BASE_URL+'/api/video/video_inte_upload',
			          testChunks: false,
			          headers:{Authorization : `Bearer `+this.$g.access_token},
			    },
			    selectFileOrNot:false,  //是否选中文件
			    uploadOrNot:false, 		//是否已经上传
			    attrs: {
			      	accept: ['video/mp4']
			    },
			    statusText: {
			      	success: '上传成功',  
			      	error: '上传出错',  
			     	uploading: '正在上传...',  
			      	paused: '暂停',  
			      	waiting: '等待上传'  
				},
 				timeMax: '00:00:00',
				currentPage4: 4,
				ruleForm: {
					opInx:0,
					endTime: '00:00:00', //结束时间
					startTime: '00:00:00', //开始时间
					len: '00:00:00'

				},
				rules: {
					startTime: [
						{ required: true, message: '请输入开始时间', trigger: 'blur' },
					],
					endTime: [
						{ required: true, message: '请输入结束时间', trigger: 'blur' },
					]
				},
				playerOptions : {
				    loop: false,
				    height: '360',
				    language: "zh-CN",
			        sources: [{
			            type: "application/x-mpegURL",
			            src: "blabla"
			        }],
			        notSupportedMessage: '此视频暂无法播放，请稍后再试',
			        autoplay: false,
			        controls: true,
			        poster: "",
					controlBar: {
			          	timeDivider: true,
			         	durationDisplay: true,
			         	remainingTimeDisplay: false,
			          	fullscreenToggle: true  //全屏按钮
				    },
				     // flash: {swf: SWF_URL },
				},
			   
			 
			  uploadMode: false,
			  selectResourceFile:false,//选择视频
			  selectResourceView: false, //选择资源
			  resourceList2: [], //选择资源--data
			  resourceType2: '', //选择资源-资源类型--val
			  typeOptions: [], //资源类型
			  resourceSearch2: "", //选择视频--搜索
			  resourceType3: '',
			  fixVideoList:[],
			  loadingIntegration: false,
			  uploadLimitMax: 2000
			}
		},
		created(){

		},

		watch:{
			
		},
		mounted(){
			this.initFunc();
		},
		beforeDestroy(){
			this.$refs.videoPlayer && this.$refs.videoPlayer.player.reset()
		},
		methods: {
			/**
			 * 改变进度条
			 */
			onSlicePlay() {
			    // this.debounce(() => {
			    //     var normal_currentTime = this.$refs.videoPlayer.player.currentTime();
			    //     var unnormal_currentTime = this.$refs.videoPlayer.player.currentTime();
			    //     if (
			    //         normal_currentTime.toString() ==
			    //         unnormal_currentTime.toString()
			    //     ) {
			    //         this.$refs.videoPlayer.player.pause();
			    //         this.$refs.videoPlayer.player.play();
			    //     }
			    // }, 100);

			},
			//延迟处理
			debounce(func, wait, immediate) {
			    let timeout, args, context, timestamp, result;
			    const later = function() {
			        // 据上一次触发时间间隔
			        const last = +new Date() - timestamp;

			        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
			        if (last < wait && last > 0) {
			            timeout = setTimeout(later, wait - last);
			        } else {
			            timeout = null;
			            // 如果设定为immediate===true，因为开始已经调用过了此处无需调用
			            if (!immediate) {
			                result = func.apply(context, args);
			                if (!timeout) context = args = null;
			            }
			        }
			    };
			    return function(...args) {
			        context = this;
			        timestamp = +new Date();
			        const callNow = immediate && !timeout;
			        // 如果延时不存在，重新设定延时
			        if (!timeout) timeout = setTimeout(later, wait);
			        if (callNow) {
			            result = func.apply(context, args);
			            context = args = null;
			        }

			        return result;
			    };
			},
			/*
				删除上传文件
			 */
			removeFile(done){

				this.$confirm('确认关闭？')
				.then(_ => {
					done();
					this.$refs.uploader.uploader.cancel();
				})
				.catch(_ => {});
				
			},
			initFunc(){

				this.$refs.videoPlayer.player.src({ type : "application/x-mpegURL", src : this.compParam.play_url }) ;
				this.resolveFixVideoList();
				this.timeMax = this.compParam.length;

			},
			resolveFixVideoList(){
				if( this.fixVideoList.length === 0 ){
					this.fixVideoList.push(
						{
							id: 		this.compParam.id,
							name : 		this.compParam.name,
							path : 		this.compParam.path,
							play_url: 	this.compParam.play_url,
							thumbnail: 	this.compParam.thumbnail,
							timerate : 	'00:00:00-00:00:00',
							timerate_show:'00:00:00-00:00:00',
							times : 	'00:00:00',
							length: this.compParam.length,
						}
					);
				
				}
				
			},
			saveInteVideo(){

				this.$confirm('视频合成所需时间根据视频大小而定，在合成期间视频将不能播放以及无法编辑，确定合成?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'confirm-them',
				}).then((res) => {
					this.loadingIntegration = true
					let success = ( data=>{
						
						this.$message.success(data.msg)
						this.$emit('changeIndexx' );
						this.loadingIntegration = false
						setTimeout(()=>{
							this.$router.push('/teach/video/index')
						}, 1000);
	            	})

	            	let fail = (data=>{
	            		this.$message.error(data.msg +' 请确认是否截取了视频时间')
	            		this.loadingIntegration = false
	            	})

	            	this.$ajax.post('api/video/video_inte',{ id:this.compParam.id,inte_data:this.fixVideoList },{func:{success:success, fail: fail}})

				}).catch(() => {});
				
				
			},
			switchPlayurl(obj , inx){

				this.timeMax = this.fixVideoList[inx].length;
				var $url = this.fixVideoList[inx].play_url;
				this.ruleForm.opInx = inx;
				if (obj.type) {
					this.$refs.videoPlayer.player.src({ type : "video/mp4", src : this.BASE_URL + obj.path }) ;
				}else{
					this.$refs.videoPlayer.player.src({ type : "application/x-mpegURL", src : $url }) ;
				}
				
				 this.$refs.videoPlayer && this.$refs.videoPlayer.player.play();

			},
			comfirmVideo(){
	    		if( is_empty( this.tempVideo ) ){
	    			this.$message.warning("请选择一个视频");
	    			return false;
	    		}
	    		if( getOneColumn( this.fixVideoList,'id' ) .indexOf( this.tempVideo.id ) > -1  ){
	    			this.$message.warning("视频已经在列表中");
	    			return false;
	    		}
	    		this.uploadMode = false;
	    		this.selectResourceView = false;
	    		let obj= {
	    			id: 		this.tempVideo.id,
	    			name : 		this.tempVideo.video_name,
	    			path : 		this.tempVideo.path,
	    			play_url: 	this.tempVideo.play_url,
	    			thumbnail: 	this.tempVideo.source_url  + this.tempVideo.picture,
	    			timerate : 	'00:00:00-00:00:00',
	    			timerate_show:'00:00:00-00:00:00',
	    			times : 	'00:00:00',
	    			length: this.tempVideo.length,
	    		}
	    		this.fixVideoList.push(obj)
	    		this.switchPlayurl( obj, this.fixVideoList.length-1 );
	    	
	    	},
	    	deleteOtherVideo(inx){
	    		// console.info(this.$refs.videoPlayer.player.src )
	    		this.fixVideoList.splice( inx,1 );
	    		this.$refs.videoPlayer.player.reset()
	    	},
			selectVideo(row, column, cell, event){
	    		this.tempVideo = row;
	    		this.$refs.multipleTable.setCurrentRow(row);
	    	},
	    	getListBox(){
	    		this.getList();
	    		this.selectResourceView = true
	    	},
			getList(){
				this.tempVideo = null;
				this.loading.status  = true;
            	let success = (data=>{
            		this.loading.status = false;
            		this.listData = data.data.data;
            		this.total_number = data.data.data_sum;
            	})
            	let fail = ( data => {
            		this.loading.status = false
            		this.$message.error(data.msg)
            	})
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	this.$ajax.get('api/video/video_list',{params: this.listParam,func:{success:success,fail:fail}})
            },
            getVideoPlayTime(type = 1){
				var nowTime = formatSeconds( this.$refs.videoPlayer.player.currentTime() );
				//console.info(nowTime)
				if( type === 1){
					this.ruleForm.startTime = nowTime.hour+':'+nowTime.minute+':'+nowTime.second
				}else{
					this.ruleForm.endTime = nowTime.hour+':'+nowTime.minute+':'+nowTime.second
				}
			},
			//上传成功的事件  
			fileSuccess (rootFile, file, message, chunk) { 
				var mess = JSON.parse(message);
					mess = handleResponseData(mess)
			 	if(parseInt( mess.data.status ) ===1 ){
			  		this.uploadOrNot = true;
			  		let obj = {
			  			name : 		mess.data.file_name,
			  			play_url: 	mess.data.play_url,
			  			path: 		mess.data.file_path,
			  			thumbnail: 	mess.data.thumbnail,
			  			timerate : 	'00:00:00-00:00:00',
			  			timerate_show:'00:00:00-00:00:00',
			  			times : 	'00:00:00',
			  			length: 	mess.data.length,
			  			type: 'file'
			  		}
			  		this.fixVideoList.push(obj);
			  		
					this.$refs.uploader.uploader.cancel();
					this.selectFileShow = true;
					this.selectResourceFile = false;
					this.uploadMode = false;

					this.switchPlayurl(obj, this.fixVideoList.length-1 );
			  }
			},
			
			fileFail( rootFile, file, message, chunk ){
				var mess = JSON.parse(message);
				// console.info(mess)
				if( parseInt( mess.error ) === 401 && this.uploadRetryTimes > 0){
					let callbcak = ( data=>{
						this.uploadRetryTimes--;
						this.$refs.videoPlayer.player.retry( file );
	            	})
					this.get_access_token( callbcak );
				}else {
			    	this.$message.error( mess.msg )
			    	this.loadingIntegration = false
			    }
			},
			fileAdd( file,fileList ){
				
				this.selectFileOrNot = true;
				this.selectFileShow = false;
			},

			//过滤文件格式
			fileSubmit(files, fileList, event){


				for (var i = 0 ; i < fileList.length ; i++ ) {
					var ext = fileList[i].name.split('.').pop().toLocaleLowerCase();
					var file_type = ['wmv', 'mpeg', 'mpg','avi','mov','ram','mp4', 'mkv' ]

					if( !file_type.includes(ext)){
						this.$message.warning('不允许上传的文件格式')
						this.$refs.uploader.uploader.removeFile( fileList[i] );
					}else if (fileList[i].size === 0) {
						this.$refs.uploader.uploader.cancel();
						this.$message.error('上传文件大小不能小于0')
					}else if(fileList[0].size >  this.uploadLimitMax*1024*1024  && this.uploadLimitMax > 0){
						this.$message.warning('只允许上传'+this.uploadLimitMax+'M以内的文件');
						this.$refs.uploader.uploader.cancel();

					}else{
						
						// if( fileList[i].size >  this.uploadLimitMax*1024*1024  && this.uploadLimitMax > 0 ){
						// 	this.$message.warning('只允许上传'+this.uploadLimitMax+'M以内的文件');
						// 	this.$refs.uploader.uploader.removeFile( fileList[i] );
						// }
						
					}
				}
				
			},
			fileRemoved(file){
				this.selectFileOrNot = false;
				this.selectFileShow = true;
			},
			fileUpload(){
				this.$refs.uploader.uploader.resume();
			},
			//分页
			handleSizeChange(val) {
		    	this.listParam.page_index = 1;
		    	this.listParam.page_size = val;
		    	this.getList()
		    },
		    handleCurrentChange(val) {
		    	this.listParam.page_index = val;
		    	this.getList();
		    },
			//表格
			handleClick(row) {
				// console.log(row);
			},
			//视频
			// listen event
			onPlayerPlay(player) {
				this.onSlicePlay()
				// console.log('player play!', player)
			},
			onPlayerPause(player) {
				// console.log('player pause!', player)
			},
			// ...player event

			// or listen state event
			playerStateChanged(playerCurrentState) {
				// console.log('player current update state', playerCurrentState)
			},
			// player is ready
			playerReadied(player) {
				console.log('the player is readied', player)
				// you can use it to do something...
				// player.[methods]
			},


			handleSelect(key, keyPath) {
				// console.log(key, keyPath);
			},
			//表单验证
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						var newTime = this.ruleForm.startTime.split(':');
						var total_time_num = parseInt(newTime[0])*3600+parseInt(newTime[1])*60+parseInt(newTime[2]);
						var newTime2 = this.ruleForm.endTime.split(':');
						var total_time_num2 = parseInt(newTime2[0])*3600+parseInt(newTime2[1])*60+parseInt(newTime2[2]);

						if (total_time_num2 < total_time_num) {
							this.ruleForm.endTime = ''
							 this.$message.error('开始时间不能大于结束时间');
							return
						}
						var diff_time = formatSeconds( total_time_num2-total_time_num );

						this.fixVideoList[this.ruleForm.opInx].timerate = this.ruleForm.startTime + '-' + this.ruleForm.endTime;
						this.fixVideoList[this.ruleForm.opInx].times = diff_time.hour+':'+diff_time.minute+':'+diff_time.second
						this.ruleForm.len = diff_time.hour+':'+diff_time.minute+':'+diff_time.second
						this.calTimerateShow();
					} else {
						return false;
					}
				});
			},
			//计算最终视频中的时长 TODO
			calTimerateShow(){
				for( var i = 0 ; i < this.fixVideoList.length ; i++ ){
					if( i === 0 ){
						this.fixVideoList[i].timerate_show = '00:00:00-'+this.fixVideoList[i].times;
					}else{
						//上个结束时间
						var lastEndtime = this.fixVideoList[i-1].timerate_show.split('-')[1];
						// console.info(lastEndtime)
						//上个结束时间剪切
						var lastEndtimeF = lastEndtime.split(':');
						// console.info(lastEndtimeF)
						//当前开始时间秒数
						var thisStartSecond = (parseInt(lastEndtimeF[0])*3600+parseInt(lastEndtimeF[1])*60+parseInt(lastEndtimeF[2]))+1;
						// console.info(thisStartSecond)

						var timeSecondF = this.fixVideoList[i].times.split(':');
						var timeEndSecond = parseInt(timeSecondF[0])*3600+parseInt(timeSecondF[1])*60+parseInt(timeSecondF[2])+thisStartSecond
						this.fixVideoList[i].timerate_show = formatSecondsToHour(thisStartSecond)+ '-'+ formatSecondsToHour(timeEndSecond)
					}
				}
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			//选择试题--input-- checked
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
		}
	}
</script>